#include "StompedReality/Core/Input/Keys.h"
#include "StomperLib/Elements/ObjectBaseTool.h"

namespace StomperLib {

namespace Elements
{
ObjectBaseTool::ObjectBaseTool( StomperLib::BaseLayout* layout, StompedReality::IGame* game,
                                StomperLib::EditorCamera* camera )
  : StomperLib::ToolElement( layout, game, camera )
{
  this->m_IsTranslating = false;
  this->CreateGui( layout );
}

ObjectBaseTool::~ObjectBaseTool( )
{
}

void ObjectBaseTool::Draw( )
{
  this->RenderObjects( );
  this->RenderSelectedObjects( );
}

void ObjectBaseTool::CreateGui( StomperLib::BaseLayout* layout )
{
  auto window = layout->CreateSubWindow( "Patch Properties", "Ctrl + Shift + p", true );

  m_Propeties = new StomperLib::Controls::ObjectProperties( (Gwen::Controls::WindowControl*) window );
  m_Propeties->Dock( Gwen::Pos::Fill );
  Model->ObjectList->onSelectionChange.Add( this, &ObjectBaseTool::UpdatePropertyObject );
}

bool ObjectBaseTool::Update( )
{
  if (Model->Mode & DeleteMode)
  {
    return DeleteOnMouseClick( );
  }

  if (Model->ObjectList->IsObjectSelected( ) && GetInputSystem( )->IsKeyDown( KEY_DEL ))
  {
    Model->ObjectList->Remove( Model->ObjectList->GetSelectedObjectIndex( ));
    this->Model->NotifyModification( this->Model->CurrentWorkingFile );
    return true;
  }

  if (Model->ObjectList->IsObjectSelected( ) && (Model->Mode == TranslateMode))
  {
    if (this->UpdateTranlating( ))
      return true;
  }

  return this->SelectOnMouseClick( );
}

bool ObjectBaseTool::SelectOnMouseClick( )
{
  if (Model->Mode & DeleteMode)
    return false;
  if (this->GetInputSystem( )->IsLeftButtonPressed( ))
  {
    int index = Model->ObjectList->Select( this->SelectionFunction );
    if (index != -1)
    {
      return true;
    }
  }
  return false;
}

void ObjectBaseTool::UpdatePropertyObject( )
{
  this->m_Propeties->SetEditorObject( Model->ObjectList->GetSelectedObject( ));
  this->onSelectionChanged.Call( m_Propeties );
}

bool ObjectBaseTool::DeleteOnMouseClick( )
{
  if (this->GetInputSystem( )->IsLeftButtonPressed( ))
  {
    int index = Model->ObjectList->FindIndex( this->SelectionFunction );
    if (index != -1)
    {
      Model->ObjectList->Remove( index );
      this->Model->NotifyModification( this->Model->CurrentWorkingFile );
      return true;
    }
  }
  return false;
}

bool ObjectBaseTool::UpdateTranlating( )
{
  if (GetInputSystem( )->IsLeftButtonUp( ) && this->m_IsTranslating)
  {
    this->m_IsTranslating = false;
    return false;
  }

  if (GetInputSystem( )->IsLeftButtonDown( ) &&
      Model->ObjectList->GetSelectedObject( )->IntersectsWithMouse( GetMousePos( )))
  {
    this->m_IsTranslating = true;
  }

  if (this->m_IsTranslating)
  {
    Model->ObjectList->GetSelectedObject( )->Translate( this->GetInputSystem( )->GetMouseDelta( ));
    this->Model->NotifyModification( this->Model->CurrentWorkingFile );
    this->m_Propeties->RefreshProperties( );
    return true;
  }

  return false;
}

}
}